
class Breakpoint {
	static getInstance(Vue) {
		if (!this.instance) {
			this.instance = new Breakpoint(Vue);
		}
		return this.instance;
	}
	constructor(Vue) {
		this.instance = null;
		this.config = {}
		if (!Vue) return
		this.$vue = Vue
		this.state = Vue.observable({
			// // 断点
			xs: false,
			sm: false,
			md: false,
			lg: false,
			xl: false,
			// 如果屏幕宽度 < mobileBreakpoint 时为 true
			mobile: false,
			mobileBreakpoint: 960,
			// 当前断点的名称 (例如. 'md')
			name: 'xs',
			// 尺寸
			height: 0,
			width: 0,
			// 阈值
			// 可通过选项配置
			thresholds: {
				xs: 600,
				sm: 960,
				md: 1264,
				lg: 1904
			},
			// 滚动条
			scrollBarWidth: 24
		})
		return this
	}
	setConfig(config) {
		if (!config.thresholds) {
			config.thresholds = {
				xs: 600,
				sm: 960,
				md: 1264,
				lg: 1904
			}
		} else {
			if (!config.thresholds.xs) {
				config.thresholds.xs = 600
			}
			if (!config.thresholds.sm) {
				config.thresholds.sm = 960
			}
			if (!config.thresholds.md) {
				config.thresholds.md = 1264
			}
			if (!config.thresholds.lg) {
				config.thresholds.lg = 1904
			}
		}
		if (!config.mobileBreakpoint) {
			config.mobileBreakpoint = 960
		}
		this.config = config
	}
	getBreakpoint() {
		let sys = uni.getSystemInfoSync()
		let {
			windowWidth,
			windowHeight
		} = sys
		this.state = this._setPonit(this.state, windowWidth, windowHeight)
		uni.onWindowResize((res) => {
			let {
				windowWidth,
				windowHeight
			} = res.size
			this.state = this._setPonit(this.state, windowWidth, windowHeight)
		})

		return this.state
	}
	_setPonit(state, width, height) {
		state.width = width
		state.height = height
		state.mobile = width <= this.config.mobileBreakpoint
		Object.assign(state, this._getPoint(state.width), this.config)
		return state
	}
	_getPoint(width) {
		let obj = {
			name: 'xs',
			xs: false,
			sm: false,
			md: false,
			lg: false,
			xl: false,
		}
		let thresholds = this.config.thresholds
		if (0 < width && width <= thresholds.xs) {
			obj.name = 'xs'
			obj.xs = true
		} else if (thresholds.xs < width && width <= thresholds.sm) {
			obj.name = 'sm'
			obj.sm = true
		} else if (thresholds.sm < width && width <= thresholds.md) {
			obj.name = 'md'
			obj.md = true
		} else if (thresholds.md < width && width <= thresholds.lg) {
			obj.name = 'lg'
			obj.lg = true
		} else if (width > thresholds.lg) {
			obj.name = 'xl'
			obj.xl = true
		} else {
			obj.name = 'xs'
			obj.xs = true
		}
		return obj
	}
}

export default Breakpoint
